<?php


namespace app\model;


use app\constant\TenantConst;
use app\constant\WxUserConst;
use app\helper\CommonHelper;
use Exception;
use think\Db;

class AppWxUser extends Base
{
    public function checkWxUser($data)
    {

        try {
            if ($data == null || $data['unionid'] == null) {
                return false;
            }

        $model = $this::get(['unionid' => $data['unionid'],'tid'=>$data['tid']]);
            if ($model) {
                $userData = $model->getData();
                if($userData['type']==WxUserConst::TYPE_VIP){
                    //TODO 判断会员是否过期 后续用定时任务来做吧
                    $has = AdminUserVip::get(['tid'=>$data['tid'],'id'=>$userData['id']]);
                    if(!$has){
                        $model->setAttr('type',WxUserConst::TYPE_NORMAL);
                        $model->allowField(true)->save();
                        $userData['type']=WxUserConst::TYPE_NORMAL;
                    }else{
                        $now = new \DateTime();
                        $exp = new \DateTime($has->expiration_time);
                        if($now->getTimestamp()>$exp->getTimestamp()){
                            $model->setAttr('type',WxUserConst::TYPE_NORMAL);
                            $model->allowField(true)->save();
                            $userData['type']=WxUserConst::TYPE_NORMAL;
                        }
                    }
                }
                return ['done' => true,'user_info'=>$userData];
            }
        } catch (Exception $e) {
        }
        return $this->createWxUser($data);
    }

    private function createWxUser($data)
    {
        // 启动事务
        Db::startTrans();
        try {
            $user = [];
            $user['create_ip'] = request()->ip(1);
            $user['openid'] = $data['openid'];
            $uuid = CommonHelper::create_guid();
            $user['unionid'] = $data['unionid'];
            $user['sex'] = $data['sex'];
            $user['head_img'] = $data['headimgurl'];
            $user['nickname'] = $data['nickname'];
            $user['city'] = $data['city'];
            $user['province'] = $data['province'];
            $user['country'] = $data['country'];
            $user['tid'] = $data['tid'];
            //生成邀请id，通过uuid使用md5
            $user['inv_code'] = strtoupper(substr(md5($uuid),8,16));
            //默认为普通用户
            $user['type'] = TenantConst::LEVEL_NORMAL;

            $res = $this::create($user);
            if ($res) {
                //如果有邀请id，那么要写入分销关系
                if(isset($data['invid'])){
                    $model = self::get(['inv_code'=>$data['invid']]);
                    if($model){
                        $puserData = $model->getData();
                        $appDbModel = AdminDistribution::get(['uid'=>$puserData['id']]);
                        //这里有两种情况，一种是邀请当前用的用户是顶级用户，他没有上级，另一种是有上级
                        if($appDbModel){
                            $dbdata = $appDbModel->getData();
                            $done = AdminDistribution::create(['uid'=>$res['id'],'pid_1'=>$dbdata['uid'],'pid_2'=>$dbdata['pid_1'],'pid_3'=>$dbdata['pid_2'],'tid'=>$data['tid']]);
                            if(!$done){
                                throw new Exception();
                            }
                        }else{
                            $done = AdminDistribution::create(['uid'=>$res['id'],'pid_1'=>$puserData['id'],'tid'=>$data['tid']]);
                            if(!$done){
                                throw new Exception();
                            }
                        }
                    }
                }
                Db::commit();
                return ['done' => true,'user_info'=>$res];
            }
        } catch (Exception $e) {
        }
        Db::rollback();
        return ['done' => false, 'id' => null];
    }
}